package threads;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.util.LinkedList;

import com.audiobuddy.serializables.Song;


import domain.ServerDomainController;

public class AcceptSongsThread extends Thread{

	private static final int PORT = 5555;
	private ServerDomainController dc;
	private DatagramPacket outPacket;
	private DatagramSocket datagramSocket;
	private byte[] buffer;
	private DatagramPacket inPacket;

	public AcceptSongsThread(ServerDomainController dc) {
		super("acceptSongs");
		this.dc = dc;
	}

	@Override
	public void run() {
		super.run();
		while(true){
			try{
				if(datagramSocket!=null)datagramSocket.close();
				datagramSocket = new DatagramSocket(PORT);
				buffer = new byte[4096];
				inPacket = new DatagramPacket(buffer, buffer.length);
				datagramSocket.receive(inPacket);
				
				InetAddress clientAddress = inPacket.getAddress();
				int clientPort = inPacket.getPort();
				
				ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
				ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bais));
				
				Song[] songs = (Song[]) ois.readObject();
				Song song = songs[0];
				song.setClientIP(inPacket.getAddress());
				dc.addSong(song);
				datagramSocket.close();
				
			}catch (IOException e) {
				System.out.println("IOException on receiving song: " + e);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	
	

}
